//
//  MailSelectoColorClassView.m
//  WoWeiRenRenOC
//
//  Created by 姜孟东 on 2020/6/12.
//  Copyright © 2020 姜孟东. All rights reserved.
//

#import "MailSelectoColorClassView.h"
#import "MailGoodsAttributeModel.h"

#import "PropertyHeader.h"
#import "PropertyCell.h"
#import "UIScrollView+UITouch.h"
#import "UICollectionViewLeftAlignedLayout.h"

@interface MailSelectoColorClassView()<UICollectionViewDelegate,UICollectionViewDataSource,ORSKUDataFilterDataSource>

@property (strong, nonatomic) UICollectionView *collectionView;

@property (nonatomic, strong) NSArray *dataSource;
@property (nonatomic, strong) NSArray *skuData;;
@property (nonatomic, strong) NSMutableArray *requestSkuArray;

@property (nonatomic, strong) NSMutableArray <NSIndexPath *>*selectedIndexPaths;;



@end

@implementation MailSelectoColorClassView

- (void)awakeFromNib {
    
    [super awakeFromNib];
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.bgView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(8, 8)];

    CAShapeLayer *layer = [[CAShapeLayer alloc] init];
    layer.frame = self.bgView.bounds;
    layer.path = path.CGPath;
    self.bgView.layer.mask = layer;
    self.bgView.clipsToBounds = YES;
   
    
    CAGradientLayer *gl = [CAGradientLayer layer];
    gl.frame = CGRectMake(0,0,KSCREEN_WIDTH - 30,40);
    gl.startPoint = CGPointMake(0.22, 0.36);
    gl.endPoint = CGPointMake(0.85, 0.72);
    gl.colors = @[(__bridge id)[UIColor colorWithRed:221/255.0 green:169/255.0 blue:72/255.0 alpha:1.0].CGColor, (__bridge id)[UIColor colorWithRed:189/255.0 green:135/255.0 blue:35/255.0 alpha:1.0].CGColor];
    gl.locations = @[@(0), @(1.0f)];
    self.nextBtn.layer.cornerRadius = 4;
    [self.nextBtn.layer insertSublayer:gl atIndex:0];
    self.nextBtn.clipsToBounds = YES;
    
    self.addImgView.userInteractionEnabled = YES;
    UITapGestureRecognizer *addTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(addCount)];
    [self.addImgView addGestureRecognizer:addTap];
    
    self.subtractionBtn.userInteractionEnabled = YES;
    UITapGestureRecognizer *subtractionTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(subtractionCount)];
    [self.subtractionBtn addGestureRecognizer:subtractionTap];
    
    self.count = @"1";
    self.countTF.text = self.count;
    self.countTF.userInteractionEnabled = NO;

}

- (void)setModel:(MailGoodsDetailsModel *)model {
    
    _model = model;
    SD_SETIMAGE_PlaceHolder(self.imgView, model.img_path, @"default_image_square")
    self.priceLabel.text  = [CommonTTool getPrice:model.vip_price];
    self.priceInfoLabel.text = @"会员补贴价";

    if (model.is_yk == 2) {
        self.priceLabel.text = [CommonTTool getPrice:model.yk_price];
    }
    if (model.sku_type == 2) {
        self.priceLabel.text = [CommonTTool getPrice:model.buy_price];
        self.priceInfoLabel.text = @"团购价";
    }
    
    if (self.isAddPt || self.isStartPt) {
        self.priceLabel.text = [CommonTTool getPrice:model.pt_price];
        self.priceInfoLabel.text = @"拼团价";
        self.addImgView.hidden = YES;
        self.countTF.hidden = YES;
        self.subtractionBtn.hidden = YES;
        self.oneCount.hidden = NO;
    }else {
        self.addImgView.hidden = NO;
        self.countTF.hidden = NO;
        self.subtractionBtn.hidden = NO;
        self.oneCount.hidden = YES;
    }
    
    if (self.num == 0) {
        self.num = 1;
    }
    
    
     
    
}

#pragma mark - 添加
- (void)addCount {
    
    self.num++;
    self.countTF.text = [NSString stringWithFormat:@"%d",self.num];
    
    self.subtractionBtn.image = [UIImage imageNamed:@"jian1"];

}

#pragma mark - 减少
- (void)subtractionCount {
    
    
    if (self.num == 1) {
        SVP(@"购买数量最少为1");
        
        return;
    }
    self.num--;
    self.countTF.text = [NSString stringWithFormat:@"%d",self.num];
    if (self.num == 1) {
        self.subtractionBtn.image = [UIImage imageNamed:@"jian"];
    }

}

- (void)tap {
    
}


- (void)setIsShoppingCar:(BOOL)isShoppingCar {
    
    _isShoppingCar = isShoppingCar;
    if (isShoppingCar) {
        self.priceLabel.text = [CommonTTool getPrice:self.model.vip_price];
        self.priceInfoLabel.text = @"会员补贴价";
        if (self.model.is_yk == 2) {
            self.priceLabel.text = [CommonTTool getPrice:self.model.yk_price];
        }
        if (self.model.sku_type == 2) {
            self.priceLabel.text = [CommonTTool getPrice:self.model.buy_price];
            self.priceInfoLabel.text = @"团购价";
        }
    }
    [self valiIsShow];

    
}


- (void)setIsBuyClik:(BOOL)isBuyClik {
    
    _isBuyClik = isBuyClik;
    if (isBuyClik) {
        self.priceLabel.text = [CommonTTool getPrice:self.model.vip_price];
        self.priceInfoLabel.text = @"会员补贴价";
        if (self.model.is_yk == 2) {
            self.priceLabel.text = [CommonTTool getPrice:self.model.yk_price];
        }
        if (self.model.sku_type == 2) {
            self.priceLabel.text = [CommonTTool getPrice:self.model.buy_price];
            self.priceInfoLabel.text = @"团购价";
        }
    }
    [self valiIsShow];

}


- (void)setIsAddPt:(BOOL)isAddPt {
    
    _isAddPt = isAddPt;
    if (isAddPt) {
        self.priceLabel.text = [CommonTTool getPrice:self.model.pt_price];
        self.priceInfoLabel.text = @"拼团价";
    }
    
    [self valiIsShow];

}

- (void)setIsStartPt:(BOOL)isStartPt {
    
    _isStartPt = isStartPt;
    if (isStartPt) {
        self.priceLabel.text = [CommonTTool getPrice:self.model.pt_price];
        self.priceInfoLabel.text = @"拼团价";
    }
    
    [self valiIsShow];
    
}


- (void)valiIsShow {
    
    if (self.isAddPt || self.isStartPt) {
        
        self.addImgView.hidden = YES;
        self.countTF.hidden = YES;
        self.subtractionBtn.hidden = YES;
        self.oneCount.hidden = NO;
    }else {
        self.addImgView.hidden = NO;
        self.countTF.hidden = NO;
        self.subtractionBtn.hidden = NO;
        self.oneCount.hidden = YES;
    }
    
}


- (UICollectionView *)collectionView {
 
    if (!_collectionView) {
        
         
        UICollectionViewLeftAlignedLayout  *layout = [[UICollectionViewLeftAlignedLayout alloc] init];
        // 设置具体属性
        // 1.设置 最小行间距
        layout.minimumLineSpacing = 10;
        // 2.设置 最小列间距
        layout. minimumInteritemSpacing  = 10;
        // 3.设置item块的大小 (可以用于自适应)
        layout.estimatedItemSize = CGSizeMake(20, 60);
        layout.headerReferenceSize = CGSizeMake(kScreenW, 30);
        // 设置滑动的方向 (默认是竖着滑动的)
        layout.scrollDirection =  UICollectionViewScrollDirectionVertical;
        // 设置item的内边距
        layout.sectionInset = UIEdgeInsetsMake(10,10,10,10);
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 200) collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [_collectionView registerNib:[UINib nibWithNibName:@"PropertyCell" bundle:nil] forCellWithReuseIdentifier:@"PropertyCell"];

        [_collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([PropertyHeader class]) bundle:nil]
        forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"PropertyHeader"];
        
    }
    
    return _collectionView;
}
    


- (void)setGoodsAttrubuteArray:(NSArray *)goodsAttrubuteArray {
    
    _goodsAttrubuteArray = goodsAttrubuteArray;
    
    if (goodsAttrubuteArray.count == 0) {
        self.oneBgView.hidden = YES;
    }
    self.buttonArrayS = [NSMutableArray array];
    for (UIView *view in self.oneBgView.subviews) {
        [view removeFromSuperview];
    }
    
    
    
    self.requestSkuArray = [NSMutableArray array];
    NSMutableArray *skuArray = [NSMutableArray array];
    for (MailGoodsAttributeModel  *model in goodsAttrubuteArray) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:model.attribute_name forKey:@"name"];
        NSMutableArray *sku_attribute_value_list = [NSMutableArray array];

        for (MailGoodsAttributeChildModel *sku_attribute in model.sku_attribute_value_list) {
           
            [sku_attribute_value_list addObject:sku_attribute.attribute_value];
            [self.requestSkuArray addObject:sku_attribute.attribute_value_id];
        }
        [dict setObject:sku_attribute_value_list forKey:@"value"];
        [skuArray addObject:dict];
    }


    _dataSource = skuArray;
  
    
    
    
    
    CGFloat h = 0;
    CGFloat w = 5;
    for (int i = 0; i < goodsAttrubuteArray.count; i++) {
        MailGoodsAttributeModel *model  = goodsAttrubuteArray[i];
        h += 40;
        int tag = i + 1;
        tag = tag * 10000;
        for (int o = 0; o < model.sku_attribute_value_list.count; o++) {
            MailGoodsAttributeChildModel *childModel = model.sku_attribute_value_list[o];
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
           
           
            NSDictionary *attributes = @{NSFontAttributeName:kPRFont(14)};
            CGFloat length = [childModel.attribute_value boundingRectWithSize:CGSizeMake(kScreenW - 30, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.width;
            button.titleLabel.font = kPRFont(14);

            //为button赋值
            [button setTitle:childModel.attribute_value forState:UIControlStateNormal];
            //设置button的frame
            button.frame = CGRectMake(10 + w, h, length + 25 , 25);
            //当button的位置超出屏幕边缘时换行 320 仅仅是button所在父视图的宽度
            if(10 + w + length + 25 > kScreenW - 30){
                w = 15; //换行时将w置为0
                h = h + button.frame.size.height + 10;//距离父视图也变化
                button.frame = CGRectMake(10 + w, h, length + 25, 25);//重设button的frame
            }
            w = button.frame.size.width + button.frame.origin.x;
//            [self.oneBgView addSubview:button];
            if (o == model.sku_attribute_value_list.count - 1) {
                h += 25  + 10;
                w = 5;
            }

        }
        
        
    }
    
    self.oneBgViewHeight.constant = h;
    CGFloat viewH = h + 120 + 165;
    self.bgScrollviewHeight.constant = viewH;
    if (viewH > kScreenH) {
        self.bgScrollviewHeight.constant = kScreenH;
    }
    self.bgViewHeight.constant = viewH;
    self.bgScrollview.contentSize = CGSizeMake(kScreenW, viewH);
    [self.oneBgView addSubview:self.collectionView];
    self.collectionView.frame = CGRectMake(0, 0, kScreenW, h);

//    [self setSelectSku:NO];
    [self setSelectSku];
}

- (void)setSelectSku {
    
    dispatch_group_t downloadGroup = dispatch_group_create();
    NSMutableArray *array = [NSMutableArray array];
    for (NSInteger i = 0; i < self.requestSkuArray.count; i++) {
        dispatch_group_enter(downloadGroup);
        NSDictionary *para = @{@"sku_code":self.model.sku_code,
                                @"sku_type":@(self.model.sku_type),
                                @"is_yk":@(self.model.is_yk),
                                @"business_id":self.model.business_id,
                                @"attribute_value_ids":self.requestSkuArray[i]
           };
        [NetRequestTool postUrl:@"sku/querySkuAttributeGoods" parameters:para success:^(id responseObject) {
            NSArray *modelArray = responseObject[@"object"];
        
            [array addObjectsFromArray:modelArray];



        } failure:^(NSInteger statusCode) {

        } finish:^{
            dispatch_group_leave(downloadGroup);
            
        }];
        
        
    }
    
    dispatch_group_notify(downloadGroup, dispatch_get_main_queue(), ^{
        
        NSMutableArray* temp = [[NSMutableArray alloc] init];
        for (NSDictionary* model in array)
        {
          if (![temp containsObject:model])
          {
              [temp addObject:model];
          }
        }
        NSMutableArray *skuArray = [NSMutableArray array];
        for (NSDictionary *model in temp) {
           NSMutableDictionary *skuModel = [NSMutableDictionary dictionary];
           NSArray *goodsSkuArray = [model[@"gg_info"] componentsSeparatedByString:@"|"];
           NSMutableArray*contition = [NSMutableArray array];
            for (int i = 0; i < self.dataSource.count; i++) {
               [contition addObject:@""];
           }
           for (NSString *goodsSku in goodsSkuArray) {
               for (int i = 0; i<self.dataSource.count; i++) {
                   NSString *skuName = [NSString stringWithFormat:@"%@:",self.dataSource[i][@"name"]];
                   if ([goodsSku containsString:skuName]) {
                       NSString *skuValue = [goodsSku substringFromIndex:skuName.length];
                       [contition replaceObjectAtIndex:i withObject:skuValue];

                   }
               }
           }
           NSString *contitionSre = @"";
           for (NSString  *skuStr in contition) {
               contitionSre = [contitionSre stringByAppendingFormat:@"%@^",skuStr];
           }
           contitionSre = [contitionSre substringToIndex:contitionSre.length-1];
           [skuModel setObject:contitionSre forKey:@"contition"];
           [skuModel setObject:model[@"attribute_value_ids"] forKey:@"price"];
           [skuModel setObject:contitionSre forKey:@"store"];
           [skuArray addObject:skuModel];
        }

        

        dispatch_async(dispatch_get_main_queue(), ^{
            self.skuData = skuArray;
            self.filter = [[ORSKUDataFilter alloc] initWithDataSource:self];
            self.filter.needDefaultValue = YES;
            [self.collectionView reloadData]; //更新UI显示
            [self action_complete:nil];       //更新结果查询]
        });
       

    });

    
    
   

        
}


#pragma mark -- collectionView

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return _dataSource.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSArray *array = _dataSource[section][@"value"];
    return [array count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
        
    PropertyCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PropertyCell" forIndexPath:indexPath];
    NSArray *data = _dataSource[indexPath.section][@"value"];
    cell.propertyL.text = data[indexPath.row];
    
    if ([_filter.availableIndexPathsSet containsObject:indexPath]) {
//        [cell setTintStyleColor:[UIColor blackColor]];
        [cell setCellStatus:1];
    }else {
//        [cell setTintStyleColor:[UIColor lightGrayColor]];
        [cell setCellStatus:2];
    }
    
    if ([_filter.selectedIndexPaths containsObject:indexPath]) {
//        [cell setTintStyleColor:[UIColor redColor]];
        [cell setCellStatus:3];
    }
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        PropertyHeader *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"PropertyHeader" forIndexPath:indexPath];
        view.headName.text = _dataSource[indexPath.section][@"name"];
        return view;

    }else {
        UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footerIdf" forIndexPath:indexPath];
        
        return view;
    }
    
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NSArray *dataArray = _dataSource[indexPath.section][@"value"];
    NSString *data = dataArray[indexPath.row];
    
    
    NSDictionary *attributes = @{NSFontAttributeName:kPRFont(14)};
    CGFloat length = [data boundingRectWithSize:CGSizeMake(kScreenW - 30, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.width;
   
    return CGSizeMake(length+25,25);

}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    [_filter didSelectedPropertyWithIndexPath:indexPath];
    
    [collectionView reloadData];
    [self action_complete:nil];
}

#pragma mark -- ORSKUDataFilterDataSource

- (NSInteger)numberOfSectionsForPropertiesInFilter:(ORSKUDataFilter *)filter {
    return _dataSource.count;
}

- (NSArray *)filter:(ORSKUDataFilter *)filter propertiesInSection:(NSInteger)section {
//    NSString  *value = _dataSource[section][@"value"];
//    if ([value containsString:@","]) {
//        _dataSource[section][@"value"] = @"111";
//    }
    if (section < _dataSource.count) {
        id dataArray =  _dataSource[section][@"value"];
        if ([dataArray isKindOfClass:[NSArray class]]) {
            return dataArray;
        }else {
            return [NSArray array];
        }
    }else {
        return [NSArray array];
        
    }
    
    
}

- (NSInteger)numberOfConditionsInFilter:(ORSKUDataFilter *)filter {
    return _skuData.count;
}

- (NSArray *)filter:(ORSKUDataFilter *)filter conditionForRow:(NSInteger)row {
    NSString *condition = _skuData[row][@"contition"];
    return [condition componentsSeparatedByString:@"^"];
}

- (id)filter:(ORSKUDataFilter *)filter resultOfConditionForRow:(NSInteger)row {
    NSDictionary *dic = _skuData[row];
    return @{@"price": dic[@"price"],
             @"store": dic[@"store"]};
}

#pragma mark -- action
- (IBAction)action_complete:(id)sender {
    
//    NSLog(@"%@", _filter.currentAvailableResutls);

    NSDictionary *dic = _filter.currentResult;
    
    if (dic == nil) {
        
        return;
    }
    if (self.refreshMailGoodsModel) {
        self.refreshMailGoodsModel();
    }
    
}






@end
